﻿using System.Threading.Tasks;
using Respawn;
using Respawn.Graph;
using SBlogCore.Common.App.Manager;
using SBlogCore.Common.DatabaseAccessor;
using SBlogCore.Common.DatabaseAccessor.Entitys;

namespace SBlogCore.IntegrationTest
{
    public class XUnitHelper
    {
        private  Respawner respawner;
        private string _conn;
        private GlobalDbContext _dbContext;
        public XUnitHelper(GlobalDbContext dbContext)
        { 
            
            _conn= AppSetting.ReadAppSettings("ConnectionStrings:SBlogCore");
            _dbContext= dbContext;
            respawner =  Respawner.CreateAsync(_conn, new RespawnerOptions
            {
                TablesToIgnore = new Table[]{"__EFMigrationsHistory"}
            }).GetAwaiter().GetResult();
        }
        public GlobalDbContext DbContext => _dbContext;
        /// <summary>
        /// 重置数据库
        /// </summary>
        /// <returns></returns>

        public  async Task ResetAsync()
        {
            await respawner.ResetAsync(_conn);
        }
        /// <summary>
        /// 保存上下文
        /// </summary>
        /// <returns></returns>
        public   async Task SaveChangeAsync()
        {
            await _dbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public  async Task<T?> FindAsync<T>(long id) where T : BaseEntity
        {
           var data= await _dbContext.FindAsync<T>(id);
           return data;
        }
    }
}
